const fs = require('fs');
const { join } = require('path');
const got = require('got');

// 生成目录
const distDir = join(__dirname, '..', 'dist');

// cookie 存储地址
const cookiefile = join(__dirname, 'cookie.txt');

// 获取 cookie
let cookie = getCookie();

// 神剑接口地址
const host = 'https://www.shenjian.io/index.php';

// headers
const headers = {
  cookie,
  'user-agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
  referer: host,
  'X-Requested-With': 'XMLHttpRequest',
};

// 获取 cookie
function getCookie() {
  if (!fs.existsSync(cookiefile)) {
    return '';
  }

  return fs.readFileSync(cookiefile, 'utf8') || '';
}

// 设置 cookie
function setCookie(value) {
  if (!value) {
    return false;
  }

  cookie = value;
  fs.writeFileSync(cookiefile, cookie, 'utf8');
}

/**
 * 抓取方法
 * @param {string|object} action 动作
 * @param {object} body POST数据
 */
async function fetch(action, body) {
  const query = typeof action === 'string' ? { r: action } : action;
  return got.post(host, { query, body, headers, json: true, form: true });
}

// 是否登录
async function checkLogin() {
  const { body } = await fetch('consolev2/getCollections');
  return body.result === 1;
}

/**
 * 登录
 */
async function login({ username, password }) {
  const form = {
    name_login: username,
    password: password,
    remember: 'on',
    _from: 'home',
  };

  const { headers, body } = await fetch('sign/inAjax', form);

  const cookies = headers['set-cookie'].join('');
  let session = (cookies.match(/PHPSESSID=[^;]+/) || [''])[0];
  if (!session) {
    session = (cookie.match(/PHPSESSID=[^;]+/) || [''])[0];
  }
  const token = (cookies.match(/login_token=[^;]+/) || [''])[0];
  cookie = [
    session,
    token,
    `_name_login=${encodeURIComponent(form.name_login)}`,
  ].join('; ');
  setCookie(cookie);

  return body;
}

/**
 * 保存代码
 * @param {number|string} appid 应用id
 * @param {string} code 代码
 */
async function codeSave(appid, code) {
  const query = { r: 'crawler/codeSave', app_id: appid };
  const data = {
    code_size: '',
    proxy_type: 0,
    log_type: '',
    log_level: '',
    code,
  };
  const { body } = await fetch(query, data);
  return body;
}

// (async () => {
//   await login({ username: 'cik520@qq.com', password: '121314' });
//   const isLogin = await checkLogin();
//   console.log(isLogin);
//   const data = await codeSave('1791608', 'var a = 123;');
//   console.log(data);
// })();















/**
 * 发布代码
 */
async function release({ file }) {
  file = `${distDir}/${file.replace('.ts', '.js')}`;

  if (!fs.existsSync(file)) {
    throw Error('请先编译代码！');
  }

  const content = fs.readFileSync(file, 'utf8');
  const appid = (content.match(/ @appid (\d+)/) || [])[1];
  const url = `https://www.shenjian.io/index.php?r=crawler/codeSave&app_id=${appid}`;

  const id = appid;
  const cookie = 'PHPSESSID=2u2v0c80fjqrad6ct8d6e6o8v0';
  const code = content;

  const data = {
    code_size: '',
    proxy_type: 0,
    log_type: '',
    log_level: '',
    code,
  };

  const { body } = await got.post(`${url}${id}`, {
    body: data,
    headers: { cookie },
    form: true,
    json: true,
  });

  return body.reason;
}

module.exports = {
  release,
  login,
  checkLogin,
};
